// pages/grid/grid.js
const app = getApp();
Page({
  data: {
    windowWidth: app.windowWidth,
    windowHeight: app.windowHeight,
    seconds: 0,
    timestr: "00:00", // 可以除去小时这个位置
    nowDifficulty: 3,
    maxScore: wx.getStorageSync("maxScore") || [
      9999,
      9999,
      9999,
      9999,
      9999,
      9999,
      9999,
    ],
    mimeMap: ["这是存储数字方格的一维数组"],
    status: 0, //0 游戏未开始或已经结束； 1 游戏运行中；2 游戏暂停
    succ_steps: 0, // 我的得分
    timebegin: 0, //开始时间
    time_add_er: null,
  },
  x: 0, // 用户点中的列
  y: 0, // 用户点中的行

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    initGame(this);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},

  digGold: function (event) {
    if (this.data.status != 1) {
      console.log("游戏尚未开始，不可点击", this.data.status);
      return;
    }
    let N = this.data.nowDifficulty;
    let value = parseInt(event.target.dataset.value);
    console.log(event.target.dataset);
    // wx.showToast({ title: JSON.stringify(event.target.dataset) });
    if (value == this.data.succ_steps + 1) {
      // console.log(this.data.succ_steps);
      // this.reportMyChoice(value);
      this.setData({
        succ_steps: value,
      });
      // 游戏结束
      if (value == N * N) {
        this.setData({
          status: 0,
        });
        var now = new Date();
        var leave = (now.getTime() - this.data.timebegin.getTime()) / 1000;
        console.log(leave);
        this.modalcnt(leave, this);
      }
    }
  },

  // reportMyChoice: function (value) {
  //   this.setData({
  //     succ_steps: this.value,
  //   });
  //   console.log(this.value);
  // },

  modalcnt: function (s, that) {
    let nowMaxScore = that.data.maxScore[that.data.nowDifficulty];
    let N = that.data.nowDifficulty;
    wx.showModal({
      title: "游戏结束",
      content:
        s < nowMaxScore
          ? "新记录！！你的时间：" + s
          : "你的时间：" + s + " 秒，最高记录：" + nowMaxScore + " 秒",
      success: function (res) {
        initGame(that);
        if (res.confirm) {
          console.log("用户点击确定");
          let newMaxList = that.data.maxScore;
          let newMax = Math.min(s, newMaxList[N - 3]);
          newMaxList[N - 3] = newMax;
          wx.setStorageSync("maxScore", newMaxList);
          // that.data.maxScore = newMaxList;
          that.setData({
            maxScore: newMaxList,
          });
          console.log(newMaxList);
        } else if (res.cancel) {
          console.log("用户点击取消");
          that.goBack();
        }
      },
    });
  },
  goGame: function () {
    startGame(this);
  },
  setDifficulty: function () {
    let that = this;
    wx.showActionSheet({
      itemList: ["4 × 4", "5 × 5", "6 × 6", "7 × 7", "8 × 8", "9 × 9"],
      success(res) {
        console.log("修改难度为 >>> ", res.tapIndex + 4);
        that.setData({ nowDifficulty: res.tapIndex + 4 });
        initGame(that);
      },
    });
  },
  goBack: function () {
    // 切换页面
    wx.navigateTo({
      url: "../index/index",
    });
  },
}); //page

// 游戏控制
function initGame(that) {
  setmap(that, false);
}
function startGame(that) {
  setmap(that, true);
  setStatus_beginTime(that);
  checkTime(that);
}

// 数组，洗牌算法
function randoms(send) {
  //var r = new Random();
  var temp1, temp2;
  var len = send.length;
  var n = len;
  var returnValue = new Array();
  for (var i = 0; i < n; i++) {
    temp1 = (Math.random() * len) | 0;
    returnValue[i] = send[temp1];
    temp2 = send[temp1];
    send[temp1] = send[len - 1];
    send[len - 1] = temp2;
    len--;
  }
  return returnValue;
}

function formatSeconds(that) {
  var mins = 0,
    seconds = that.data.seconds;
  if (seconds < 60) {
  } else if (seconds < 3600) {
    mins = parseInt(seconds / 60);
    seconds = seconds % 60;
  }
  that.setData({
    timestr: formatTime(mins) + ":" + formatTime(seconds),
  });
}

function formatTime(num) {
  if (num < 10) return "0" + num;
  else return num + "";
}

function checkTime(that) {
  var seconds = that.data.seconds;
  if (seconds > 3599) {
    that.setData({
      time: "已经一小时了 Good Game ~ ",
    });
    return;
  }
  if (that.data.status == 1) {
    if (that.data.time_add_er != null) {
      clearTimeout(that.data.time_add_er);
    }
    that.data.time_add_er = setTimeout(function () {
      that.setData({
        seconds: seconds + 1,
      });
      checkTime(that);
    }, 1000);
    formatSeconds(that);
  }
}

function setStatus(that) {
  // that.data.timebegin = new Date();
  // that.data.status = 1;
  that.setData({
    status: 1,
    timebegin: new Date(),
  });
  // if (that.data.seconds < 600) {
  // that.data.cost = 1;
  // }
}

function setmap(that, mode) {
  let N = that.data.nowDifficulty;
  let baseArray = new Array();
  for (let i = 0; i < N; i++) {
    for (let j = 0; j < N; j++) baseArray.push(i * N + j + 1);
  }
  // 如果mode为true则打乱，游戏开始，否则，输出自然顺序的baseArray
  if (mode) {
    console.log("游戏开始");
    baseArray = randoms(baseArray);
  }
  console.log(baseArray);
  that.setData({
    mimeMap: baseArray,
    succ_steps: 0,
    seconds: 0,
    timestr: "00:00",
  });
  if (mode) {
    that.setData({
      status: 1,
    });
  } else {
    that.setData({
      status: 0,
    });
  }
}
